package com.asj.vivo.lock.service.oppoSdk;

import static com.asj.enums.AppIdentifierDictEnums.all_restrictAppEnabledStart;
import static com.asj.enums.AppIdentifierDictEnums.all_restrictAppNotAllowedStart;
import static com.asj.enums.AppIdentifierDictEnums.app_packageName;
import static com.asj.enums.AppIdentifierDictEnums.supervision_initiate;
import static com.asj.enums.AppIdentifierDictEnums.supervision_isSave;
import static com.asj.enums.ControlProgressBarEnum.restrict_software_success;
import static com.asj.enums.ControlProgressBarEnum.restrict_system_success;
import static com.asj.enums.DeviceIdentifierDictEnums.lockMachine;
import static com.asj.enums.DeviceIdentifierDictEnums.unlockMachine;
import static com.asj.enums.NotificationSwitchEnums.LOCK_NOTIFICATION;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.DISABLE_APP_IN_LAUNCHER_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.DISABLE_APP_IN_RECENT_TASK_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.ENABLE_APP_IN_LAUNCHER_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.ENABLE_APP_IN_RECENT_TASK_FLAG;

import android.content.Context;

import androidx.annotation.NonNull;

import com.asj.MainActivity;
import com.asj.enums.ControlProgressBarEnum;
import com.asj.service.binding.AppInfoHandlerService;
import com.asj.utils.CommonsUtils;
import com.oplus.customize.coreapp.utils.ConstantUtil;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 业务层面控制OPPO接口的服务
 * */
public class OPPOControlService {

    public Context context;
    public MainActivity mainActivity;

    private final String packName = app_packageName.getValue();

    public OPPOControlService(Context context,MainActivity mainActivity) {
        this.context = context;
        this.mainActivity = mainActivity;
    }
    public OPPOControlService(Context context) {
        this.context = context;
    }
    public OPPOControlService(MainActivity mainActivity){
        if(context == null){
            this.context = mainActivity;
        }
        this.mainActivity = mainActivity;
    }

    public static String lockState = unlockMachine.getValue();


    /**
     * 启动/取消监管
     * @param isSaveOp 是否是保存设备时进行的操作
     * @param opType 是启动还是取消监管
     * */
    public void initiateOrCancelSupervision(String isSaveOp,String opType){
        try{
            //针对软件层面的限制
            superviseSoftware(opType);
            if(isSaveOp.equals(supervision_isSave.getValue())){
                ControlProgressBarEnum.setValueAndMessage(restrict_software_success);
            }
            //针对手机层面的限制
            superviseOperatingSystem(opType);
            if(isSaveOp.equals(supervision_isSave.getValue())){
                ControlProgressBarEnum.setValueAndMessage(restrict_system_success);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 进行锁机
     * */
    public void lockMachine(String password,String phone,String remark){
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        try{
            //强制关闭侧边栏
            opposdkService.setSideBarPolicies("true");
            //禁止进入关机页面
            opposdkService.setPowerDisable(true);
            //禁用锁屏界面忘记密码功能
            opposdkService.setDisableKeyguardForgetPassword("true");
            //如果时绑定时的锁定，还是需要屏幕进行固定的
            if(password == null || phone == null){
                //添加固定屏幕显示应用
                opposdkService.addScreenPinningApp(packName);
                //禁止使用电源键进入休眠
                opposdkService.setSleepByPowerButtonDisabled("true");
            }
            //当设置了密码的时候，判断为锁机，进行强制锁定
            if(password != null && phone != null){
                lockState = lockMachine.getValue();
                //设置密码
                opposdkService.setPassword("true",password);
                //设置移动网络强制打开
                opposdkService.setMobileDataMode(1);
                //设置屏幕顶层，提示锁机联系电话
                opposdkService.setTopWatermarkEnable("密码:"+password+"解锁查看通知");
                //强制锁定
                opposdkService.DeviceLocked("true");
                //限制所有应用不允许运行
                restrictDeviceAllAppInfo(all_restrictAppNotAllowedStart.getValue());
                //禁止乐划锁屏
                opposdkService.setSystemUpdatePolicies(true);
                //设置来电拨打限制
                lockPhone(opposdkService,phone);
                //一键清理后台
                opposdkService.cleanBackgroundProcess();
                //声明打电话的通知
                CommonsUtils.showPersistentCallNotification(context,"当前设备已被锁定，点击该通知拨打对方电话","商户留言："+remark,phone);
            }
        }catch (Exception e){
            unlockMachine(password != null && phone != null);
            throw new RuntimeException("锁机异常|"+e);
        }
    }
    //设置电话限制
    public void lockPhone(OPPOSDKService opposdkService,String phone){
        //设置白名单模式
        opposdkService.setContactBlockPattern(2);
        //添加白名单电话
        opposdkService.addContactBlockNumberList(phone,2);
    }

    /**
     * 取消锁机
     * */
    public void unlockMachine(boolean isLocked){
        try {
            OPPOSDKService opposdkService = getOpposdkService();
            //如果是锁机操作进行解锁才取消所有应用限制
            if(isLocked){
                lockState = unlockMachine.getValue();
                //清除锁屏密码
                opposdkService.setPassword("false", null);
                //取消限制，所有应用允许运行
                restrictDeviceAllAppInfo(all_restrictAppEnabledStart.getValue());
                //取消移动网络强制打开
                opposdkService.setMobileDataMode(2);
                //允许乐划锁屏
                opposdkService.setSystemUpdatePolicies(false);
                //取消电话限制
                unlockPhone(opposdkService);
                //关闭电话通知
                CommonsUtils.cancelNotificationById(context,LOCK_NOTIFICATION.getCode());
            }
        }catch (Exception e){
            throw new RuntimeException("解锁异常|"+e);
        }
    }
    private @NonNull OPPOSDKService getOpposdkService() {
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        //取消固定屏幕显示应用
        opposdkService.clearScreenPinningApp(packName);
        //不管控侧边栏
        opposdkService.setSideBarPolicies("false");
        //取消禁止进入关机页面
        opposdkService.setPowerDisable(false);
        //取消禁止使用电源键进入休眠
        opposdkService.setSleepByPowerButtonDisabled("false");
        //取消屏幕顶层水印显示
        opposdkService.setTopWatermarkDisable();
        //禁用锁屏界面忘记密码功能
        opposdkService.setDisableKeyguardForgetPassword("false");
        return opposdkService;
    }
    //取消电话限制
    public void unlockPhone(OPPOSDKService opposdkService){
        //设置普通模式，黑白名单均不生效
        opposdkService.setContactBlockPattern(0);
        //删除所有白名单列表
        opposdkService.removeContactBlockAllNumber(2);
    }

    /**
     * 针对软件层面的限制监管
     * */
    public void superviseSoftware(String opType){
        try{
            OPPOSDKService oppoSdkService = new OPPOSDKService(context);
            //等于1则进行监管
            if (supervision_initiate.getValue().equals(opType)) {

                //设置EMM 客户端为 Active Admin
                oppoSdkService.setEmmAdmin(true);

                //设置为 DeviceOwner
                oppoSdkService.setDeviceOwner();

                //设置应用为可信任列表
                oppoSdkService.setSuperWhiteList(Collections.singletonList(packName));

                //静默允许第三方应用权限
                oppoSdkService.grantAllRuntimePermission(packName);

                // 常驻后台
                oppoSdkService.addPersistentApp(packName);

                // 开启防卸载
                oppoSdkService.addDisallowedUninstallPackages(packName);

                // 添加进入Alarm白名单
                oppoSdkService.addAppAlarmWhiteList(packName);

                // 设置用户不允许自己进行系统升级
                oppoSdkService.setSystemUpdatePolicies(0);

                // 指定当前应用无视省电优化
                oppoSdkService.settingBatteryOptimizations(packName,true);

                //打开应用通知总开关
                oppoSdkService.setPackageNotificationEnable(packName,true);

                // 隐藏应用显示(不仅在桌面隐藏，而且在后台隐藏)
                oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_LAUNCHER_FLAG);
                oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_RECENT_TASK_FLAG);
            } else {
                //清空应用启动名单
                oppoSdkService.clearAllowedRunningApp();

                //取消设置应用为 DeviceOwner
                oppoSdkService.clearDeviceOwner();

                //取消应用拥有activeAdmin权限
                oppoSdkService.setEmmAdmin(false);

                //取消设置应用为可信任列表
                oppoSdkService.clearSuperWhiteList(Collections.singletonList(packName));

                // 删除常驻后台
                oppoSdkService.removePersistentApp(packName);

                // 删除防卸载应用名单
                oppoSdkService.removeDisallowedUninstallPackages(packName);

                // 删除进入Alarm白名单
                oppoSdkService.removeAppAlarmWhiteList(packName);

                // 解除用户不允许自己进行系统升级的限制
                oppoSdkService.setSystemUpdatePolicies(1);

                // 指定当前应用无视省电优化
                oppoSdkService.settingBatteryOptimizations(packName,false);

                // 恢复隐藏应用显示
                oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_LAUNCHER_FLAG);
                oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_RECENT_TASK_FLAG);
            }
        }catch (Exception e){
            throw new RuntimeException("软件层面的限制监管异常|"+e);
        }
    }

    /**
     * 针对操作系统层面的限制监管
     * */
    public void superviseOperatingSystem(String opType){
        try{
            OPPOSDKService opposdkService = new OPPOSDKService(context);
            // 执行监管操作
            if (supervision_initiate.getValue().equals(opType)) {
                //开启电话薄黑白名单功能
                opposdkService.setContactBlackListEnable(true);
                //禁止恢复出厂
                opposdkService.setRestoreFactoryDisabled("true");

                //禁止关闭定位服务
                opposdkService.setGpsPolicies("1");

                //禁用扩展存储
                opposdkService.setExternalStorageDisabled("true");

                //设置 adb 安装/卸载应用控制策略 (1：不允许通过adb方式安装应用)
                opposdkService.setAdbInstallUninstallPolicies(1);

                //强制设置USB配置(仅充电)
                opposdkService.setUSBTransferPolicy(ConstantUtil.USBTransferPolicy.UNLIMITED);

                //禁止调用adb端口
                opposdkService.setAdbDisabled("true");

                //禁止USB传输数据
                opposdkService.setUSBDataDisabled("true");

                //禁止开发者选项
                opposdkService.setDevelopmentOptionsDisabled("true");

                //禁止使用OTG
                opposdkService.setUSBOtgDisabled("true");

                //禁止还原无线设置
                opposdkService.setNetworkSettingsResetDisabled("true");

                //禁止备份恢复
                opposdkService.setBackupRestoreDisabled("true");

                //设置黑名单模式，黑名单禁止模式
                opposdkService.setAppRestrictionPolicies(1);
            }
            // 取消监管操作
            else {
                //开启电话薄黑白名单功能
                opposdkService.setContactBlackListEnable(false);

                //取消禁止恢复出厂
                opposdkService.setRestoreFactoryDisabled("false");

                //取消禁止关闭定位服务
                opposdkService.setGpsPolicies("2");

                //取消禁用扩展存储
                opposdkService.setExternalStorageDisabled("false");

                //取消设置 adb 安装/卸载应用控制策略 (1：不允许通过adb方式安装应用)
                opposdkService.setAdbInstallUninstallPolicies(0);

                //取消强制设置USB配置(仅充电)
                opposdkService.setUSBTransferPolicy(ConstantUtil.USBTransferPolicy.UNLIMITED);

                //取消禁止调用adb端口
                opposdkService.setAdbDisabled("false");

                //取消禁止USB传输数据
                opposdkService.setUSBDataDisabled("false");

                //取消禁止开发者选项
                opposdkService.setDevelopmentOptionsDisabled("false");

                //禁止使用OTG
                opposdkService.setUSBOtgDisabled("false");

                //取消禁止还原无线设置
                opposdkService.setNetworkSettingsResetDisabled("false");

                //取消禁止备份恢复
                opposdkService.setBackupRestoreDisabled("false");

                //取消黑名单模式限制
                opposdkService.setAppRestrictionPolicies(0);
            }
        }catch (Exception e){
            throw new RuntimeException("操作系统层面的限制监管异常|"+e);
        }
    }

    /**
     * 删除在设备上的锁应用
     * */
    public void seeYouLater() {
        new OPPOSDKService(context).uninstallPackage(packName);
    }

    /**
     * 设置黑名单选项
     */
    public void setBlackList(int model, List<String> blackList){
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        //添加安装黑名单
        opposdkService.addAppRestriction(model,blackList);
        //添加运行黑名单
        opposdkService.addDisallowedRunningApp(blackList);
        //强行停止指定应用
        opposdkService.forceStopPackage(blackList);
    }

    /**
     * 设置取消黑名单选项
     * */
    public void cancelSetBlackList(int model,List<String> whiteList){
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        //取消安装黑名单
        opposdkService.removeAppRestriction(model, whiteList);
        //取消运行黑名单
        opposdkService.removeDisallowedRunningApp(whiteList);
    }

    /**
     * 清空黑名单取消黑名单选项（测试使用）
     */
    public void clearBlackList(){
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        //取消安装黑名单
        opposdkService.removeAllAppRestriction(1);
        //取消运行黑名单
        opposdkService.removeAllDisallowedRunningApp();
    }

    /**
     * 限制所有应用禁止/允许启动
     * */
    public void restrictDeviceAllAppInfo(String mode){
        //获取所有本地的第三方app
        LinkedList<String> deviceAppList = AppInfoHandlerService.getInstance(context).getDeviceAppList(2);
        //排除报名中包含phone的以及指定几个报名下的应用
        deviceAppList = deviceAppList.stream().filter(app->!app.contains("phone")).collect(Collectors.toCollection(LinkedList::new));
        List<String> phonePackageName = List.of(
                //通话
                "com.android.incallui"
                ,"com.android.providers.telephony"
                ,"com.android.contacts"
                ,"com.newcall"
                ,"com.oppo.dialer"
                ,"com.android.phone"
                ,"com.android.contacts"
                ,"com.android.emergency"
                ,"com.android.stk"
                ,"com.android.mms"
                ,"com.ChinaMobile"
                ,"com.coloros.emergency"
                ,"com.android.emergency"
                ,"com.oppo.dialer"
                ,"com.oppo.sos"
                ,"com.android.providers.emergency"
                ,"com.unicom"
                ,"com.ct.client"
                ,"com.android.server.telecom"
                ,"com.android.systemui"
        );
        deviceAppList.removeAll(phonePackageName);

        //将所有应用，移除允许启动名单中
        OPPOSDKService opposdkService = new OPPOSDKService(context);
        //禁止启动
        if(all_restrictAppNotAllowedStart.getValue().equals(mode)){
            //设置应用进入不允许启动名单
            opposdkService.addDisallowedRunningApp(deviceAppList);
            //强行停止所有应用
            opposdkService.forceStopPackage(deviceAppList);
        }
        //允许启动
        else if(all_restrictAppEnabledStart.getValue().equals(mode)){
            //清空禁止启动名单
            opposdkService.removeAllDisallowedRunningApp();
        }
    }

    /**
     * 恢复出厂设置
     * */
    public void setRecovery(){
        OPPOSDKService service = new OPPOSDKService();
        service.wipeDeviceData();
    }

}
